<template>
	<view class="register text-main-color">
		<view class="nav-h flex-between">
			<view class="icon-xl circle flex-center back-btn" @click="backPage">
				<uni-icons type="arrow-left" size="24" color="#fff"></uni-icons>
			</view>
		</view>
		<view class="fs20 fb mt15">{{$t('accountReg')}}</view>
		<view class="" >
			<view class="" style="margin-top: 30px;" v-if="stpe==1">
				<uni-forms  :modelValue="loginForm" ref="loginformRule" labelWidth="auto" label-position="top" :rules="rules">
					<uni-forms-item :label="$t('account')" name="account">
						<uni-easyinput class="u-input" :inputBorder="false" v-model="loginForm.account" :placeholder="$t('enter')+$t('account')"></uni-easyinput>
					</uni-forms-item>
					<uni-forms-item style="margin-top: 20px;" :label="$t('name')" name="name">
						<uni-easyinput class="u-input" :inputBorder="false" v-model="loginForm.name" :placeholder="$t('enter')+$t('name')"></uni-easyinput>
					</uni-forms-item>
				</uni-forms>
				<button style="margin-top: 36px;" :class="['btn-submit', disabled?'login-btn-disabled':'login-btn']" :loading="loading" :disabled="disabled" @click="submitForm">{{ loading ?$t('inOperation'):$t('nextStep') }}</button>
			</view>
			<view class="mt10" v-if="stpe==2">
				<uni-forms :modelValue="loginForm2" ref="loginformRule2" labelWidth="auto" label-position="top" :rules="rules2">
					<uni-forms-item :label="$t('login')+$t('pwd')" name="logpwd">
						<uni-easyinput class="u-input" :inputBorder="false" v-model="loginForm2.logpwd" type="password" :placeholder="$t('enter')+$t('login')+$t('pwd')"></uni-easyinput>
					</uni-forms-item>
					<uni-forms-item :label="$t('confirm')+$t('pwd')" name="logpwd2">
						<uni-easyinput class="u-input" :inputBorder="false" v-model="loginForm2.logpwd2" type="password" :placeholder="$t('enterAgain')+$t('login')+$t('pwd')"></uni-easyinput>
					</uni-forms-item>
					<uni-forms-item :label="$t('transaction')+$t('pwd')" name="paypwd">
						<uni-easyinput class="u-input" :inputBorder="false" v-model="loginForm2.paypwd" type="password" :placeholder="$t('enter')+$t('transaction')+$t('pwd')"></uni-easyinput>
					</uni-forms-item>
					<uni-forms-item :label="$t('confirm')+$t('pwd')" name="paypwd2">
						<uni-easyinput class="u-input" :inputBorder="false" v-model="loginForm2.paypwd2" type="password" :placeholder="$t('enterAgain')+$t('transaction')+$t('pwd')"></uni-easyinput>
					</uni-forms-item>
					<uni-forms-item :label="$t('code')" name="code">
						<uni-easyinput class="u-input" :inputBorder="false" v-model="loginForm2.code" :placeholder="$t('enter')+$t('code')">
							<template #right>
								<view>
									<image style="width: 120px;height: 36px;" :src="captchaUrl" mode="" @click="refreshCaptcha"></image>
								</view>
							</template>
						</uni-easyinput>
					</uni-forms-item>
				</uni-forms>
				<button :class="['btn-submit', disabled2?'login-btn-disabled':'login-btn']" :disabled="disabled2" @click="submitForm2">{{$t('register')}}</button>
			</view>
		</view>
		<view class="">
			<view class="flex-center mt15 highlight-color">
				<span @click="toKefu">{{$t('onLineService')}}</span>
			</view>
			<!-- <view class="flex-center mt15 text-sm">
				{{$t('regAgree')}} 
				<navigator url="/pages/personal/yszc" open-type="navigate" hover-class="other-navigator-hover">
					<text class="highlight-color text-md pl5" >{{$t('privacy')}}</text>
				</navigator>
			</view> -->
		</view>
	</view>
</template>

<script setup>
	import { ref, watch,onMounted } from 'vue';
	import useGlobalProperties from '../../utils/useGlobalProperties.js'
	import { register, getCaptcha } from '../../api/index.js'
	import config from '../../config.js';
	const { $t,$i18n } = useGlobalProperties()
	const disabled = ref(true)
	const disabled2 = ref(true)
	const stpe = ref(1)
	const loginForm = ref({
		account: '',
		name: ''
	})
	const loading = ref(false)
	const loginForm2 = ref({
		logpwd:"",
		logpwd2:"",
		paypwd:"",
		paypwd2:"",
		code:"",
		vid:""
	})
	// 监听 loginForm 对象的变化
	watch(loginForm, (newVal, oldVal) => {
	  // console.log('loginForm changed:', newVal);
	  if(loginForm.value.account && loginForm.value.name){
		  disabled.value = false
	  }else{
		  disabled.value = true
	  }
	}, { deep: true });  // 设置 deep 为 true 以便深度监听对象的变化
	// 监听 loginForm2 对象的变化
	watch(loginForm2, (newVal, oldVal) => {
	  // console.log('loginForm changed:', newVal);
	  if(loginForm2.value.logpwd && loginForm2.value.logpwd2 && loginForm2.value.paypwd && loginForm2.value.paypwd2 && loginForm2.value.code){
		  disabled2.value = false
	  }else{
		  disabled2.value = true
	  }
	}, { deep: true });  // 设置 deep 为 true 以便深度监听对象的变化
	const rules = ref({
		account: { 
			rules:[ 
				{ required: true, errorMessage: $t('enter')+$t('account'), }, 
				{
					minLength: 3,
					maxLength: 12,
					errorMessage: $t('accountWarn',{min:3,max:12}),
				},
				{
					validateFunction:function(rule,value,data,callback){
						const regex = /^[a-zA-Z0-9]*$/; // ^：开头；[a-zA-Z0-9]：允许的字符；*：0个或多个；$：结尾
						// console.log('regex.test(value)',regex.test(value));
						if (!regex.test(value)) {
							callback('请输入英文+数字')
						}
						return true
					}
				},
			], 
		},
		name: { 
			rules:[ 
				{ required: true, errorMessage: $t('enter')+$t('name'), }, 
				{
					validateFunction:function(rule,value,data,callback){
						const regex = /^[\u4e00-\u9fa5]+$/; // ^：开头；[a-zA-Z0-9]：允许的字符；*：0个或多个；$：结尾
						// console.log('regex.test(value)',regex.test(value));
						if (!regex.test(value)) {
							callback('只能输入中文')
						}
						return true
					}
				},
			],
			trigger:'blur',
		}
	})
	const rules2 = ref({
		logpwd: {  rules:[  { required: true, errorMessage: $t('enter')+$t('login')+$t('pwd'), }, ]},
		logpwd2: { rules:[ 
			{ required: true, errorMessage: $t('enterAgain')+$t('login')+$t('pwd'), },
			{ validateFunction:function(rule,value,data,callback){
				if (value != loginForm2.value.logpwd) {
					callback($t('pwdnosome'))
				}
				return true
			} },
		]},
		paypwd: {  rules:[  { required: true, errorMessage: $t('enter')+$t('transaction')+$t('pwd'), }, ]},
		paypwd2: { rules:[ 
			{ required: true, errorMessage: $t('enterAgain')+$t('transaction')+$t('pwd'), },
			{ validateFunction:function(rule,value,data,callback){
				if (value != loginForm2.value.paypwd) {
					callback($t('pwdnosome'))
				}
				return true
			} },
		]},
		code: {  rules:[  { required: true, errorMessage: $t('enter')+$t('code'), }, ]},
	})
	const loginformRule = ref(null)
	const loginformRule2 = ref(null)
	const submitForm = () =>{
		loginformRule.value.validate().then(res => {
			// console.log('表单数据信息：', res);
			loading.value = true
			setTimeout(()=>{
				stpe.value = 2
				loading.value = false
			},2000)
		}).catch(err => {
			console.log('表单错误信息：', err);
		})
	}
	const submitForm2 = () =>{
		loginformRule2.value.validate().then(res =>{
			uni.showLoading({
				title:$t('submiting'),
			})
			const params = {
				username:loginForm.value.account,
				nickname:loginForm.value.name,
				password:loginForm2.value.logpwd,
				confirm_password:loginForm2.value.logpwd2,
				safe_password:loginForm2.value.paypwd,
				confirm_safe_password:loginForm2.value.paypwd2,
				tu_code:loginForm2.value.code,
				vid:loginForm2.value.vid,
			}
			register(params).then(res =>{
				uni.hideLoading()
				uni.showToast({
					title:res.msg,
					icon:'none'
				})
				if(res.code == 1){
					uni.setStorageSync('H5STOCK_USERINFO',res.data.userinfo)
					setTimeout(()=>{
						uni.switchTab({
							url:'/pages/home/home'
						})
					},800)
					// setTimeout(()=>{
					// 	uni.reLaunch({
					// 		url:'/pages/login/login'
					// 	})
					// },1500)
				}
			})
		}).catch(err => {
			console.log('表单错误信息：', err);
		})
	}
	const captchaUrl = ref('')
	const refreshCaptcha = ()=> {
		getCaptcha().then(res =>{
			// console.log('getCaptcha',res);
			loginForm2.value.vid = res.data.vid
			captchaUrl.value = config.BASE_URL+res.data.captcha
			console.log('getCaptcha',captchaUrl.value);
		})
	  // 通过添加时间戳参数来强制刷新
	  // const timestamp = new Date().getTime();
	  // captchaUrl.value = `${config.API_URL}/common/captcha?id=register&timestamp=${timestamp}`;
	}
	onMounted(()=>{
		refreshCaptcha();
	})
	const backPage = () =>{
		// 返回上一页
		// uni.navigateBack({
		//   delta: 1 // 默认值为1，表示返回上一页
		// });
		if(stpe.value!=2){
			history.back()
		}else{
			stpe.value = 1
		}
	}
	const toKefu = () => {
		// console.log('toKefu', params);
		// window.location.href = config.BASE_URL+ "/addons/kefu/index/mobile?token="+uni.getStorageSync('H5STOCK_USERINFO').token
		window.location.href = "https://de.to01.top/addons/kefu/index/mobile?token="+uni.getStorageSync('H5STOCK_USERINFO').token
	};
</script>

<style scoped>
.register{
    position: relative;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width: 100%;
    height: 100vh;
    padding: 0 28px;
	box-sizing: border-box;
}
.uni-forms-item{
	margin-bottom: 10px;
}
::v-deep uni-button:after{
	border: none!important;
}
.bottom {
	position: fixed;
	bottom: 50px;
	width: calc(100% - 56px);
}
</style>
